'''
@Author: your name
@Date: 2019-09-27 18:47:24
@LastEditTime: 2019-12-06 12:34:39
@LastEditors: your name
@Description: In User Settings Edit
@FilePath: \IntelligentElderlyCare\server\register\welfare_institution\test.py
'''
from server.pao_python.pao.service.data.mongo_db import MongoService, MongoFilter, C, N, F, as_date
from ...service.buss_pub.bill_manage import BillManageService, OperationType, Status, TypeId
import pandas as pd
from server.pao_python.pao.data import dataframe_to_list, process_db
from ...service.mongo_bill_service import MongoBillFilter
from ...service.common import get_random_id, get_cur_time, insert_many_data
import uuid


def register(jsonrpc, db_addr, db_port, db_name, db_user, db_pwd, inital_password, session):
    service = ServiceRecordService(
        db_addr, db_port, db_name, db_user, db_pwd, inital_password, session)

    @jsonrpc.method('Test.add_role_person')
    def __get_check_in_list(person, set_role_user, role, permission_list):
        print('用户数据:', person)
        print('角色-用户设置:', set_role_user)
        print('角色数据:', role)
        print('权限列表:', permission_list)
        res = service.add_person_role(
            person, set_role_user, role, permission_list)
        return res

    @jsonrpc.method('Test.happy_rate')
    def __get_happy_rate(condition):
        '''幸福院评比'''
        res = service.happy_rate(condition)
        return res

    @jsonrpc.method('Test.happy_build_process')
    def __happy_build_process(condition):
        '''幸福院建设情况'''
        res = service.happy_build_process(condition)
        return res


class ServiceRecordService(MongoService):
    ''' 服务记录 '''

    def __init__(self, db_addr, db_port, db_name, db_user, db_pwd, inital_password, session):
        self.db_addr = db_addr
        self.db_port = db_port
        self.db_name = db_name
        self.db_user = db_user
        self.db_pwd = db_pwd
        self.inital_password = inital_password
        self.session = session
        self.bill_manage_server = BillManageService(
            self.db_addr, self.db_port, self.db_name, self.db_user, self.db_pwd, self.inital_password, self.session)

    def add_person_role(self, person, set_role_user, role, permission_list):
        bill_id = self.bill_manage_server.add_bill(OperationType.add.value, TypeId.user.value, [
                                                   person, set_role_user, role, permission_list], ['PT_User', 'PT_Set_Role', 'PT_Role', 'PT_Permission'])
        return '新增成功' if bill_id else '新增失败'

    def happy_rate(self, condition):
        pf = pd.DataFrame(condition)
        pf.rename(columns={'排名': 'rank',
                           '幸福院名称': "name",
                           '运营管理': 'operation_score',
                           '业务成效': 'business_score',
                           '财务管理': 'financial_score',
                           '品牌建设': 'brand_build_score',
                           '安全管理': 'safety_score',
                           '社会评价': 'social_evaluation_score',
                           '总分': 'total_score',
                           '年份': 'year',
                           '评定': "assessment"}, inplace=True)
        name = pf['name'].values.tolist()
        pf['assessment'] = pf.apply(
            lambda x: self._get_assessment(x.total_score), axis=1)
        # 检查是否存在组织机构
        _filter_org = MongoBillFilter()
        _filter_org.match_bill(C('personnel_type') == '2')\
                   .project({'_id': 0, 'name': 1})
        org = self.query(_filter_org, 'PT_User')
        org_pf = pd.DataFrame(org)
        org_list = org_pf['name'].values.tolist()
        not_exit = []  # 不存在的机构
        for x in name:
            if not x in org_list:
                print('我进来了', x)
                not_exit.append(x)
        # 导入数据处理
        _filter = MongoBillFilter()
        _filter.match_bill(C('name').inner(name)) \
            .add_fields({'organzation_id': '$id'})\
            .project({'_id': 0, 'organzation_id': 1, 'name': 1})
        res = self.query(_filter, 'PT_User')
        user_pf = pd.DataFrame(res)
        new_pf = pd.merge(pf, user_pf, on=['name'])
        new_pf = new_pf[['organzation_id', 'year',
                         'rank', 'operation_score', 'business_score', 'financial_score', 'brand_build_score', 'safety_score', 'social_evaluation_score', 'total_score', 'assessment']]
        new_pf['id'] = new_pf.apply(lambda x: get_random_id(), axis=1)

        def process_func(db):
            nonlocal new_pf
            new_res = dataframe_to_list(new_pf)
            for i, x in enumerate(new_res):
                new_res[i]['create_date'] = get_cur_time()
            insert_many_data(db, 'BS_Happy_House_Rate', new_res)
        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        return str(not_exit) + '机构不存在' if len(not_exit) else '导入成功'

    def happy_build_process(self, condition):
        pf = pd.DataFrame(condition)
        pf.rename(columns={'镇街': 'town', '幸福院间数': "total",
                           '已建成数量': 'completed_total'}, inplace=True)
        res = dataframe_to_list(pf)
        for i, x in enumerate(res):
            res[i]['create_date'] = get_cur_time()

        def process_func(db):
            insert_many_data(db, 'BS_Happy_Build_Progress', res)
        process_db(self.db_addr, self.db_port, self.db_name,
                   process_func, self.db_user, self.db_pwd)
        return '导入成功'

    def _get_assessment(self, score):
        if score >= 85:
            return '优良'
        elif score >= 80:
            return '合格'
        else:
            return '不合格'
